package com.wis.bolt.risk;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wis.TopologyDrive;
import com.wis.pool.redisCluster.MyJedisClusterPool;
import com.wis.tools.CommonUtiles;
import com.wis.tools.RiskUtiles;
import org.apache.commons.lang.StringUtils;
import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.topology.base.BaseRichBolt;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Tuple;
import org.apache.storm.tuple.Values;
import redis.clients.jedis.JedisCluster;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @Description: traffic_wis
 * @author: fan
 * @Date: Created in 2018/12/17 10:18
 * @Modified By:
 */
public class RiskKaZhiBolt extends BaseRichBolt {
    private OutputCollector collector;
    private static RiskUtiles riskUtiles = new RiskUtiles();
    private static JSONArray jsonKaZhi = new JSONArray();
    private static String typeProduce;
    private static Map map;
    private static Map<String, String> kaZhiProMap = new HashMap<>();
    private static Map<String, String> kaZhiPointMap = new HashMap<>();
    private static JSONArray jsonArray = new JSONArray();
    private static List list = new LinkedList();
    private static boolean flag = true;
    private static Map<String, String> revisionMap = new HashMap();
    private static JedisCluster jedisCluster = null;

    @Override
    public void prepare(Map map, TopologyContext context, OutputCollector collector) {
        this.map = map;
        this.collector = collector;
        typeProduce = map.get(TopologyDrive.TYPE_PRODUCE).toString();
        try {
            if (jedisCluster == null) jedisCluster = MyJedisClusterPool.getRedisClusterObject();
            String hget = jedisCluster.hget(map.get(TopologyDrive.REDIS_KAZHI).toString(), "100000");
            if (StringUtils.isNotBlank(hget)) jsonKaZhi = JSONArray.parseArray(CommonUtiles.mapToJson(hget));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            jsonArray = jsonKaZhi;
            MyJedisClusterPool.returnJedisCluterObject(jedisCluster);
        }
    }

    @Override
    public void execute(Tuple tuple) {
        String key = tuple.getStringByField("key");
        String njd = tuple.getStringByField("nengjiandu");

        try {
            if (njd.equals("over")) {
                this.collector.emit(new Values(key, "over", "over", "over", "over", "over", "over", "over", "over"));
            } else if (njd.equals("jies")) {
                flag = true;
                this.collector.emit(new Values(key, "jies", "jies", "jies", "jies", "jies", "jies", "jies", "jies"));
            } else if (StringUtils.isNotBlank(njd)) {
                if (flag) {
                    try {
                        if (jedisCluster == null) jedisCluster = MyJedisClusterPool.getRedisClusterObject();
                        list.clear();
                        kaZhiPointMap.clear();
                        kaZhiProMap.clear();
                        revisionMap.clear();
                        // Jedis jedis = new Jedis(map.get(TopologyDrive.REDIS_IP).toString(), Integer.parseInt(map.get(TopologyDrive.REDIS_PORT).toString()));
                        // jedis.select(Integer.parseInt(map.get(TopologyDrive.REDIS_DB).toString()));
                        // 获取国省的所有卡值数据 // 获取详细所有点的卡值数据
                        kaZhiProMap = jedisCluster.hgetAll(map.get(TopologyDrive.REDIS_KAZHI).toString());// 返回的map集合
                        // 判断redis是否存在该点的卡值信息
                        if (jedisCluster.exists(map.get(TopologyDrive.REDIS_POINT_KAZHI).toString()))
                            kaZhiPointMap = jedisCluster.hgetAll(map.get(TopologyDrive.REDIS_POINT_KAZHI).toString());
                        // 修正后的指标值获取
                        Map<String, String> tmpRevisionMap = new HashMap<>();
                        if (jedisCluster.exists(map.get(TopologyDrive.REDIS_RISK_REV).toString())) {    // 判断是否存在需要修正的数据
                            // 获取所有修正后点的数据
                            revisionMap = jedisCluster.hgetAll(map.get(TopologyDrive.REDIS_RISK_REV).toString());// 返回的map集合
                        }
                        if (revisionMap.size() > 0)
                            for (Map.Entry m : revisionMap.entrySet()) {
                                String keyMap = m.getKey().toString();
                                list.add(keyMap);
                                tmpRevisionMap.put(keyMap, m.getValue().toString());
                            }
                        revisionMap = tmpRevisionMap;
                        // MyJedisPool.returnJedisOjbect(jedis);
                        // 省、市、县进行桩点卡值
                        if (kaZhiProMap.size() > 1)
                            for (Map.Entry m : kaZhiProMap.entrySet()) {
                                String keyMap = m.getKey().toString();
                                if (!keyMap.contains("100000")) {
                                    list.add(keyMap);
                                }
                            }
                        // 具体桩点进行卡值
                        if (kaZhiPointMap.size() > 0)
                            for (Map.Entry m : kaZhiPointMap.entrySet()) {
                                list.add(m.getKey());
                            }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        MyJedisClusterPool.returnJedisCluterObject(jedisCluster);
                        flag = false;
                    }
                }
                // 获取key中的时间
                String date = key.substring(6, 18);
                StringBuffer idStr = new StringBuffer();
                StringBuffer njdStr = new StringBuffer();
                StringBuffer xdsdStr = new StringBuffer();
                StringBuffer jsxtStr = new StringBuffer();
                StringBuffer fsStr = new StringBuffer();
                StringBuffer jslStr = new StringBuffer();
                StringBuffer jbStr = new StringBuffer();
                StringBuffer qwStr = new StringBuffer();

                String id = tuple.getStringByField("id");
                String[] njds = njd.split(",", -1);
                String[] jsxts = tuple.getStringByField("jiangshuixiangtai").split(",", -1);
                String[] fs = tuple.getStringByField("fengsu").split(",", -1);
                String[] jbs = tuple.getStringByField("daolujiebing").split(",", -1);
                String[] qws = tuple.getStringByField("qiwen").split(",", -1);
                String[] jsls = tuple.getStringByField("jiangshuiliang").split(",", -1);

                jsonKaZhi = CommonUtiles.jsonKaZhiSelect(key, id, list, kaZhiPointMap, kaZhiProMap, jsonArray);

                for (int i = 0; i < njds.length; i++) {
                    // 判断相态，异常值转化为300
                    jsxtStr.append(riskUtiles.JSXTKaZhi(jsxts[i]) + ",");
                    // 判断是否是订正过的桩点
                    if (list.contains("2-" + id)) {
                        // 修正后的值
                        // key:2-G10_101        value:201908221010-3
                        String mergeKey = "2-" + id;
                        String[] temRevisionValue = revisionMap.get(mergeKey).split("-", -1);
                        boolean flagCalc = CommonUtiles.isFlagCalc(date, temRevisionValue[0], i);
                        if (flagCalc) {
                            // 此次计算时间没有过期
                            njdStr.append(temRevisionValue[1] + ",");
                        } else {
                            jsonKaZhi = CommonUtiles.jsonKaZhiRevSelect(key, list, kaZhiProMap, jsonArray);
                            njdStr.append(riskUtiles.VBKaZhi(jsonKaZhi.getJSONObject(4), njds[i]) + ",");
                            if (i == 0)
                                CommonUtiles.deleteRevKey(jedisCluster, map.get(TopologyDrive.REDIS_RISK_REV).toString(), (mergeKey));
                            jsonKaZhi = CommonUtiles.jsonKaZhiSelect(key, id, list, kaZhiPointMap, kaZhiProMap, jsonArray);
                        }
                    } else {
                        njdStr.append(riskUtiles.VBKaZhi(jsonKaZhi.getJSONObject(4), njds[i]) + ",");
                    }

                    if (list.contains("3-" + id)) {
                        // fsStr.append(revisionMap.get("3-" + id) + ",");
                        String mergeKey = "3-" + id;
                        String[] temRevisionValue = revisionMap.get(mergeKey).split("-", -1);
                        boolean flagCalc = CommonUtiles.isFlagCalc(date, temRevisionValue[0], i);
                        if (flagCalc) {
                            // 此次计算时间没有过期
                            fsStr.append(temRevisionValue[1] + ",");
                        } else {
                            jsonKaZhi = CommonUtiles.jsonKaZhiRevSelect(key, list, kaZhiProMap, jsonArray);
                            fsStr.append(riskUtiles.commonKaZhi(jsonKaZhi.getJSONObject(5), fs[i], njds[i]) + ",");
                            if (i == 0)
                                CommonUtiles.deleteRevKey(jedisCluster, map.get(TopologyDrive.REDIS_RISK_REV).toString(), (mergeKey));
                            jsonKaZhi = CommonUtiles.jsonKaZhiSelect(key, id, list, kaZhiPointMap, kaZhiProMap, jsonArray);
                        }
                    } else {
                        fsStr.append(riskUtiles.commonKaZhi(jsonKaZhi.getJSONObject(5), fs[i], njds[i]) + ",");
                    }

                    if (list.contains("4-" + id)) {
                        // jbStr.append(revisionMap.get("4-" + id) + ",");
                        String mergeKey = "4-" + id;
                        String[] temRevisionValue = revisionMap.get(mergeKey).split("-", -1);
                        boolean flagCalc = CommonUtiles.isFlagCalc(date, temRevisionValue[0], i);
                        if (flagCalc) {
                            // 此次计算时间没有过期
                            jbStr.append(temRevisionValue[1] + ",");
                        } else {
                            jsonKaZhi = CommonUtiles.jsonKaZhiRevSelect(key, list, kaZhiProMap, jsonArray);
                            jbStr.append(riskUtiles.RIKaZhi(jsonKaZhi.getJSONObject(6), jbs[i], qws[i]) + ",");
                            if (i == 0)
                                CommonUtiles.deleteRevKey(jedisCluster, map.get(TopologyDrive.REDIS_RISK_REV).toString(), (mergeKey));
                            jsonKaZhi = CommonUtiles.jsonKaZhiSelect(key, id, list, kaZhiPointMap, kaZhiProMap, jsonArray);
                        }
                    } else {
                        jbStr.append(riskUtiles.RIKaZhi(jsonKaZhi.getJSONObject(6), jbs[i], qws[i]) + ",");
                    }

                    if (list.contains("5-" + id)) {
                        // qwStr.append(revisionMap.get("5-" + id) + ",");
                        String mergeKey = "5-" + id;
                        String[] temRevisionValue = revisionMap.get(mergeKey).split("-", -1);
                        boolean flagCalc = CommonUtiles.isFlagCalc(date, temRevisionValue[0], i);
                        if (flagCalc) {
                            // 此次计算时间没有过期
                            qwStr.append(temRevisionValue[1] + ",");
                        } else {
                            jsonKaZhi = CommonUtiles.jsonKaZhiRevSelect(key, list, kaZhiProMap, jsonArray);
                            qwStr.append(riskUtiles.qiWenKaZhi(jsonKaZhi.getJSONObject(7), qws[i]) + ",");
                            if (i == 0)
                                CommonUtiles.deleteRevKey(jedisCluster, map.get(TopologyDrive.REDIS_RISK_REV).toString(), (mergeKey));
                            jsonKaZhi = CommonUtiles.jsonKaZhiSelect(key, id, list, kaZhiPointMap, kaZhiProMap, jsonArray);
                        }
                    } else {
                        qwStr.append(riskUtiles.qiWenKaZhi(jsonKaZhi.getJSONObject(7), qws[i]) + ",");
                    }
                    if (list.contains("1-" + id)) {
                        // jslStr.append(revisionMap.get("1-" + id) + ",");
                        String mergeKey = "1-" + id;
                        String[] temRevisionValue = revisionMap.get(mergeKey).split("-", -1);
                        boolean flagCalc = CommonUtiles.isFlagCalc(date, temRevisionValue[0], i);
                        if (flagCalc) {
                            // 此次计算时间没有过期
                            jslStr.append(temRevisionValue[1] + ",");
                        } else {
                            jsonKaZhi = CommonUtiles.jsonKaZhiRevSelect(key, list, kaZhiProMap, jsonArray);
                            if (typeProduce.contains("3")) {
                                if (jsxts[i].contains("6")) {
                                    jslStr.append(riskUtiles.sleetKaZhi(jsonKaZhi.getJSONObject(3), njds[i]) + ",");
                                } else if (jsxts[i].contains("301")) {
                                    jslStr.append(riskUtiles.commonKaZhi(jsonKaZhi.getJSONObject(1), jsls[i], njds[i]) + ",");
                                } else if (jsxts[i].contains("302")) {
                                    jslStr.append(riskUtiles.commonKaZhi(jsonKaZhi.getJSONObject(3), jsls[i], njds[i]) + ",");
                                } else {
                                    jslStr.append("0" + ",");
                                }
                            } else if (typeProduce.contains("1") || typeProduce.contains("2")) {
                                if (jsxts[i].contains("6")) {
                                    jslStr.append(riskUtiles.sleetKaZhi(jsonKaZhi.getJSONObject(2), njds[i]) + ",");
                                } else if (jsxts[i].contains("301")) {
                                    jslStr.append(riskUtiles.commonKaZhi(jsonKaZhi.getJSONObject(0), jsls[i], njds[i]) + ",");
                                } else if (jsxts[i].contains("302")) {
                                    jslStr.append(riskUtiles.commonKaZhi(jsonKaZhi.getJSONObject(2), jsls[i], njds[i]) + ",");
                                } else {
                                    jslStr.append("0" + ",");
                                }
                            }
                            if (i == 0)
                                CommonUtiles.deleteRevKey(jedisCluster, map.get(TopologyDrive.REDIS_RISK_REV).toString(), (mergeKey));
                            jsonKaZhi = CommonUtiles.jsonKaZhiSelect(key, id, list, kaZhiPointMap, kaZhiProMap, jsonArray);
                        }
                    } else {
                        // 因为短临、实况和预报的卡值数据不同，一个是分钟级，一个是小时级别
                        if (typeProduce.contains("3")) {
                            if (jsxts[i].contains("6")) {
                                jslStr.append(riskUtiles.sleetKaZhi(jsonKaZhi.getJSONObject(3), njds[i]) + ",");
                            } else if (jsxts[i].contains("301")) {
                                jslStr.append(riskUtiles.commonKaZhi(jsonKaZhi.getJSONObject(1), jsls[i], njds[i]) + ",");
                            } else if (jsxts[i].contains("302")) {
                                jslStr.append(riskUtiles.commonKaZhi(jsonKaZhi.getJSONObject(3), jsls[i], njds[i]) + ",");
                            } else {
                                jslStr.append("0" + ",");
                            }
                        } else if (typeProduce.contains("1") || typeProduce.contains("2")) {
                            if (jsxts[i].contains("6")) {
                                jslStr.append(riskUtiles.sleetKaZhi(jsonKaZhi.getJSONObject(2), njds[i]) + ",");
                            } else if (jsxts[i].contains("301")) {
                                jslStr.append(riskUtiles.commonKaZhi(jsonKaZhi.getJSONObject(0), jsls[i], njds[i]) + ",");
                            } else if (jsxts[i].contains("302")) {
                                jslStr.append(riskUtiles.commonKaZhi(jsonKaZhi.getJSONObject(2), jsls[i], njds[i]) + ",");
                            } else {
                                jslStr.append("0" + ",");
                            }
                        }
                    }
                }
                this.collector.emit(new Values(key, tuple.getStringByField("id"), njdStr.substring(0, njdStr.length() - 1).toString(), fsStr.substring(0, fsStr.length() - 1).toString(), jslStr.substring(0, jslStr.length() - 1).toString(),
                        /*tuple.getStringByField("jiangshuixiangtai").toString()*/jsxtStr.substring(0, jsxtStr.length() - 1).toString(), qwStr.substring(0, qwStr.length() - 1).toString(), tuple.getStringByField("xiangduishidu").toString(), jbStr.substring(0, jbStr.length() - 1).toString()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            this.collector.ack(tuple);
        }

    }

    @Override
    public void declareOutputFields(OutputFieldsDeclarer declarer) {
        declarer.declare(new Fields("key", "id", "nengjiandu", "fengsu", "jiangshuiliang", "jiangshuixiangtai", "qiwen", "xiangduishidu", "daolujiebing"));
    }

}
